# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: Heater P-V.py
  @time: 2022/3/30 15:51
  @desc:
"""
import time

from math import *
from ATS.hardwarescan import conf_file_manager
from ATS.application.LCR_App.U2722A_App import U2722A_App
from ATS.application.LASER_App.L8164B_App import L8164B_App
from ATS.application.LASER_App.N7744C_App import N7744C_App
from ATS.application.VNA_App.N5225B_App import N5225BApp
from ATS.util.calcu_step_util import get_points_list
from ATS.util.save_data_2_csv_util import saveData2CSV
from matplotlib import pyplot as plt
from ATS.switchdriver.LightSwitchDriver import LightSwitchDriver
from utils.find3db_util import find3db_util
# from sympy import symbols, diff
import numpy as np


# 通道1设置扫描电压，通道2、3固定电压
def pv_test(wave_length=1340, power_value=12, sweep_channel=3, sweep_range="120mA", sweep_limit=0.12,
            start_voltage=0, stop_voltage=3.5, points=101,
            spot_channel01=1, spot_channel01_range="120mA", spot_channel01_limit=0.12, spot_channel01_valtage=2,
            spot_channel02=2, spot_channel02_range="120mA",
            spot_channel02_limit=0.12, spot_channel02_valtage=2, n7744_power_range=10, atim="100us", ):
    u2722a_app = U2722A_App("SMU4")
    l8164b_app = L8164B_App("SS3")
    n7744c_app = N7744C_App("SS2")

    inst_light = LightSwitchDriver.instance()
    if inst_light.is_connected:
        inst_light.set_all_switch("01", "05")
        time.sleep(1)
        print(inst_light.query_switch())
    else:
        inst_light.connect()
    l8164b_app.reset()
    l8164b_app.set_power_unit()
    l8164b_app.set_power_value(power_value)
    l8164b_app.set_wave_length(wave_length)

    l8164b_app.output_on()
    n7744c_app.reset()
    # 增加的调试代码======
    # n7744c_app.set_logging_state("STOP")
    # n7744c_app.trigger_input_mode("IGN")
    # ++++++++++++++++
    n7744c_app.set_power_wave_length()
    n7744c_app.set_power_unit()
    n7744c_app.set_power_range(n7744_power_range)
    n7744c_app.set_power_atim(atim)
    time.sleep(5)
    # u2722a_app.set_voltage(spot_channel01_valtage, spot_channel01)
    # u2722a_app.set_voltage(spot_channel02_valtage, spot_channel02)
    u2722a_app.set_voltage_range(sweep_channel)
    u2722a_app.set_voltage_range(spot_channel01)
    u2722a_app.set_voltage_range(spot_channel02)
    u2722a_app.set_current_range_limit(spot_channel01_range, spot_channel01_limit, spot_channel01)
    u2722a_app.set_current_range_limit(spot_channel02_range, spot_channel02_limit, spot_channel02)
    u2722a_app.set_current_range_limit(sweep_range, sweep_limit, sweep_channel)
    voltage_list = get_points_list(start_voltage, stop_voltage, points)
    u2722a_app.output_state(1, sweep_channel)

    power_list = []
    for volage in voltage_list:
        u2722a_app.set_voltage(volage, sweep_channel)
        # n7744c_app.tigger_status(1)
        # n7744c_app.init_channel_continous()
        # time.sleep(0.01)
        power_value = n7744c_app.get_power_value()
        # print("power_value", power_value)
        power_list.append(float(power_value))
    # u2722a_app.output_state(0, sweep_channel)
    # u2722a_app.output_state(0, spot_channel01)
    # u2722a_app.output_state(0, spot_channel02)
    inst_light.set_all_switch("01", "06")
    time.sleep(1)
    print(inst_light.query_switch())
    datas = find3db_util(voltage_list, power_list)
    print("data", datas[0])
    u2722a_app.set_voltage(float(round(datas[0], 3)), sweep_channel)
    u2722a_app.set_voltage(2.0, spot_channel01)
    u2722a_app.set_voltage(2.0, spot_channel02)
    u2722a_app.output_state(1, spot_channel01)
    u2722a_app.output_state(1, spot_channel02)
    time.sleep(1)
    n5225bapp = N5225BApp("VNA")
    state = n5225bapp.start_trigger()
    print("state", state)
    if state == "+1":
        print("bw", n5225bapp.search_bw())

    u2722a_app.output_state(0, sweep_channel)
    u2722a_app.output_state(0, spot_channel01)
    u2722a_app.output_state(0, spot_channel02)
    return voltage_list, power_list


def plot_curve2(curve_list, title, x, y, max_x, max_y):
    color = ["r", "m", "c", "y"]
    label = ["0s", "60s", "300s", "10s"]
    plt.figure(figsize=(20, 20), dpi=100)
    fig, ax = plt.subplots()
    ax.set_title(f"{title} P-V curve")
    for i in range(len(curve_list)):
        ax.plot(curve_list[i][0], curve_list[i][1], color[i], label=f"{label[i]}")
        ax.plot([max_x], [max_y], "s")
        ax.text(max_x, max_y, f"{str(round(max_x, 3))},{str(round(max_y, 3))}")
        ax.plot([x], [y], "s")
        ax.text(x, y, f"{str(round(x, 3))},{str(round(y, 3))}")
        ax.set_xlabel("Voltage")
        ax.set_ylabel("Power")
        ax.grid(True)
        ax.legend()
    plt.savefig(f"{title}.png")
    plt.show()


def plot_curve(curve_list):
    color = ["r", "b", "g"]
    for i in range(len(curve_list)):
        plt.plot(curve_list[i][0], curve_list[i][1], color[i])
        plt.xlabel("Voltage")
        plt.ylabel("Value")
        plt.grid(True)
    plt.show()


def cal_slope(x, y):
    slope, intercept = np.polyfit(x, y, 1)
    return slope


def find3db(x_data, y_data):
    print("12345", x_data, y_data)
    max_peak = ""
    peak_index = ""
    max_peak = max(y_data)
    peak_index = y_data.index(max(y_data))
    # for t in range(len(y_data)):
    #     if t > 1 and y_data[t - 1] < y_data[t] and y_data[t] > y_data[t + 1]:
    #         max_peak, peak_index = y_data[t], t
    #         break
    print("max_pea", max_peak)
    length = len(y_data)
    compare_value = float(max_peak) - 3
    max_x = x_data[peak_index]
    print("max_peak", max_peak, peak_index, x_data[peak_index], compare_value)
    left_x_value, left_y_value = "", ""

    index1 = 0
    for i in range(length):
        result = y_data[i] - compare_value
        # if 0.4 >= abs(result) >= 0:
        if (0 < abs(result)) and (abs(result) < 0.4):
            index1 = i
            if (cal_slope([x_data[i], x_data[i + 1]], [y_data[i], y_data[i + 1]])) > 0:
                left_x_value, left_y_value = x_data[i], y_data[i]
                break
            else:
                continue

    # for i in range(peak_index - 1, 0, -1):
    #     result = y_data[i] - compare_value
    #     if 0.4 >= abs(result) >= 0:
    #         index1 = i
    #         left_x_value, left_y_value = x_data[i], y_data[i]
    #         break

    if all([left_x_value, left_y_value, max_x, max_peak]):
        return left_x_value, left_y_value, max_x, max_peak


# print("1111",locals())
# print(locals()['para'][0].smu_setting)
# print(locals()['para'][0].l8164_setting)
# print(locals()['para'][0].n7744_setting)
# x_data, y_data = pv_test()
# n7744c_app.get_power_value()

title = "CWDM4-S3"
curve_list = []
for i in [0]:
    x_data, y_data = pv_test()
    curve_list.append([x_data, y_data])
    plot_curve(curve_list)
    datas = find3db(curve_list[0][0], curve_list[0][1])
    if datas and len(datas) == 4:
        print(datas)
        plot_curve2(curve_list, title, datas[0], datas[1], datas[2], datas[3])
        saveData2CSV(f"{title}.csv", ["Voltage(V)", "Power(dbm)"], curve_list)
    else:
        print("There is no correct value")
